3.4-canvas
Create by fall on 10 Jun 2022 Recently revised in 06 Apr 2023
canvas
Canvas 的默认大小为 300px * 150px
(宽 * 高)
如何获取 DOM
// 确保 DOM 中存在如下的标签
// <canvas id="canvas" width="600" height="600"></canvas>
const canvas = document.getElementById('canvas')
const stx = canvas.getContext('2d') // 获取 2d 对象
如何绘制矩形
ctx.fillStyle = 'green'; // 填充颜色
ctx.strokeRect(x,y) // 绘制边框,四个参数分别表示填充的起始点 x y,以及宽度,高度
ctx.fillRect(10, 10, 150, 100); // 填充矩形,四个参数分别表示填充的起始点 x y,以及宽度,高度
画一个圆形
ctx.translate(300, 300) // 原点偏移方向 x 轴 300,y 轴 300
ctx.beginPath() // 开启路径
ctx.arc(0, 0, 100, 0, 2 * Math.PI) // 起始点 x,y 半径
ctx.closePath() // 关闭路径
ctx.strokeStyle = 'red' // 更改颜色为红色
ctx.stroke() // 画: stroke 意思为轻划
canvas 对象
ctx.beginPath() // 新建一条路径生成之后,绘制命令被指到路径上生成的内容
ctx.closePath() // 闭合路径
ctx.stroke() // 通过线条进行绘制
ctx.fill() // 通过填充进行绘制
保存和提取
// 保存和提取状态,是一个栈,也就是说,只能提取栈中最近的一次保存
// 保存当前状态
ctx.save()
// 提取当前状态
ctx.restore()
drawImage
向 canvas 内画入 image 图片,可选参数类型
// dx, dy 表示插入后在画布中的位置
drawImage(image, dx, dy)
// dWidth, dHeight 表示插入后在画布中的位置
drawImage(image, dx, dy, dWidth, dHeight)
// sx, sy 等表示截取图片源文件的坐标,sWidth, sHeight 表示截取宽高,dx, dy, dWidth, dHeight 表示插入后的位置和宽高
drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight)
toDataURL
将 canvas 作为 DataURL 进行输出
const canvas = document.getElementById('canvas')
const stx = canvas.getContext('2d') // 获取 2d 对象
stx.drawImage() // 将 image 在画布上画出来
const mimeType = 'image/png'
const quality = 0.4
// 将画布上的内容转换为 DataURL
stx.toDataURL(mimeType, quality)
// mimeType:image/png,image/jpeg,image/webp
// quality:0-1,默认压缩质量为 0.92
实现将图片进行压缩,
toBlob
将 canvas 作为 Blob 进行输出,该方法是异步的
const callback =(blob)=>{
console.log(blob) // 如果未创建成功,为 null
}
// mimeType 和 quality 和 toDataURL 类似
const mimeType = "image/jpeg"
const quality = 0.3
stx.toBlob(callback,mimeType, quality)
WebGL
Web Graphics Library(是一种 3D 绘图标准)
参考文章
作者 | 链接 |
---|---|
MDN官方文档 | https://developer.mozilla.org/zh-CN/docs/Web/API/Canvas_API |
Sunshine_Lin | https://juejin.cn/post/6986785259966857247 |
刘伟C | 前端图片压缩上传(压缩篇):可能是最适合小白的前端图片压缩文章了! |